import {Button, ScrollView, Text, View} from '@tarojs/components'
import Taro, {useDidShow} from '@tarojs/taro'
import type React from 'react'
import {useCallback, useState} from 'react'
import {getMyOrders, type Order} from '@/api'
import {isLoggedIn} from '@/utils/auth'

const Orders: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([])
  const [loading, setLoading] = useState(true)

  const loadOrders = useCallback(async () => {
    // 检查登录状态
    if (!isLoggedIn()) {
      setLoading(false)
      return
    }

    setLoading(true)

    try {
      const result = await getMyOrders()

      if (result.success && result.data) {
        setOrders(result.data)
      } else {
        Taro.showToast({
          title: result.error || '查询失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('查询订单失败:', error)
      Taro.showToast({
        title: '查询失败，请重试',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }, [])

  useDidShow(() => {
    loadOrders()
  })

  const handleOrderClick = (orderNo: string) => {
    Taro.navigateTo({
      url: `/pages/order-detail/index?orderNo=${orderNo}`
    })
  }

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
  }

  const getStatusText = (status: string) => {
    const statusMap = {
      pending: '待支付',
      paid: '已支付',
      cancelled: '已取消'
    }
    return statusMap[status] || status
  }

  const getStatusColor = (status: string) => {
    const colorMap = {
      pending: 'text-amber-600 bg-amber-50',
      paid: 'text-green-600 bg-green-50',
      cancelled: 'text-gray-600 bg-gray-50'
    }
    return colorMap[status] || 'text-gray-600 bg-gray-50'
  }

  const handleLogin = () => {
    Taro.navigateTo({url: '/pages/login/index'})
  }

  // 未登录状态
  if (!isLoggedIn()) {
    return (
      <View style={{background: 'linear-gradient(to bottom, #EFF6FF, #FFFFFF)', minHeight: '100vh'}}>
        <ScrollView scrollY className="box-border" style={{height: '100vh', background: 'transparent'}}>
          <View className="px-4 py-12">
            <View className="text-center mb-8">
              <View className="w-24 h-24 bg-gray-200 rounded-full mx-auto mb-4 flex items-center justify-center">
                <View className="i-mdi-lock text-6xl text-gray-400"></View>
              </View>
              <Text className="text-xl font-bold text-gray-900 block mb-2">请先登录</Text>
              <Text className="text-sm text-gray-500 block">登录后可查看您的订单</Text>
            </View>

            <Button
              onClick={handleLogin}
              className="w-full bg-blue-600 text-white py-3 rounded-xl font-bold text-base"
              style={{
                backgroundColor: '#2563eb',
                color: 'white',
                border: 'none'
              }}>
              立即登录
            </Button>
          </View>
        </ScrollView>
      </View>
    )
  }

  // 加载中状态
  if (loading) {
    return (
      <View style={{background: 'linear-gradient(to bottom, #EFF6FF, #FFFFFF)', minHeight: '100vh'}}>
        <ScrollView scrollY className="box-border" style={{height: '100vh', background: 'transparent'}}>
          <View className="px-4 py-12 text-center">
            <View className="i-mdi-loading text-6xl text-blue-600 mb-4 animate-spin"></View>
            <Text className="text-gray-500 block">加载中...</Text>
          </View>
        </ScrollView>
      </View>
    )
  }

  return (
    <View style={{background: 'linear-gradient(to bottom, #EFF6FF, #FFFFFF)', minHeight: '100vh'}}>
      <ScrollView scrollY className="box-border" style={{height: '100vh', background: 'transparent'}}>
        <View className="px-4 py-6">
          <View className="bg-white rounded-2xl shadow-sm p-4 mb-4">
            <Text className="text-base font-bold text-gray-900 block">我的订单</Text>
          </View>

          {orders.length === 0 ? (
            <View className="text-center py-12">
              <View className="i-mdi-inbox text-6xl text-gray-300 mb-4"></View>
              <Text className="text-gray-500 block">暂无订单记录</Text>
            </View>
          ) : (
            <View className="space-y-4">
              {orders.map((order) => (
                <View
                  key={order.id}
                  className="bg-white rounded-2xl shadow-sm overflow-hidden transition-all active:scale-98"
                  onClick={() => handleOrderClick(order.order_no)}>
                  <View className="p-4">
                    <View className="flex items-center justify-between mb-3">
                      <Text className="text-base font-bold text-gray-900">{order.exhibition_title}</Text>
                      <View className={`px-3 py-1 rounded-full ${getStatusColor(order.status)}`}>
                        <Text className="text-xs font-bold">{getStatusText(order.status)}</Text>
                      </View>
                    </View>

                    <View className="flex items-center mb-2">
                      <View className="i-mdi-map-marker text-gray-500 mr-2"></View>
                      <Text className="text-sm text-gray-600">{order.exhibition_location}</Text>
                    </View>

                    <View className="flex items-center mb-2">
                      <View className="i-mdi-ticket text-gray-500 mr-2"></View>
                      <Text className="text-sm text-gray-600">
                        {order.items?.reduce((sum, item) => sum + item.quantity, 0) || 0} 张票
                      </Text>
                    </View>

                    <View className="flex items-center mb-3">
                      <View className="i-mdi-clock-outline text-gray-500 mr-2"></View>
                      <Text className="text-sm text-gray-600">{formatDate(order.created_at)}</Text>
                    </View>

                    <View className="flex items-center justify-between pt-3 border-t border-gray-100">
                      <View>
                        <Text className="text-xs text-gray-500 block mb-1">订单号</Text>
                        <Text className="text-xs text-gray-700">{order.order_no}</Text>
                      </View>
                      <View className="flex items-center">
                        <Text className="text-xs text-gray-500 mr-2">总计</Text>
                        <Text className="text-xl font-bold text-blue-600">
                          ¥{Number(order.total_amount).toFixed(2)}
                        </Text>
                      </View>
                    </View>
                  </View>

                  <View className="bg-gray-50 px-4 py-3 flex items-center justify-between">
                    <Text className="text-sm text-gray-600">点击查看详情</Text>
                    <View className="i-mdi-chevron-right text-xl text-gray-400"></View>
                  </View>
                </View>
              ))}
            </View>
          )}
        </View>
      </ScrollView>
    </View>
  )
}

export default Orders
